package cn.glutnn.gataway.auth;

/**
 * Author:   msh
 * Date:     2025/1/13 下午12:41
 * Description:
 */

import cn.dev33.satoken.stp.StpInterface;
import cn.glutnn.gataway.entity.AuthPermission;
import cn.glutnn.gataway.entity.AuthRole;
import cn.glutnn.gataway.redis.RedisUtil;
import com.alibaba.nacos.shaded.com.google.gson.reflect.TypeToken;
import com.google.gson.Gson;
import io.micrometer.common.util.StringUtils;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 自定义权限验证接口扩展
 */
@Component
public class StpInterfaceImpl implements StpInterface {
    @Resource
    private RedisUtil redisUtil;
    private String authPermissionPrefix = "auth:permission:";
    private String authRolePrefix = "auth:role:";

    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        return getAuth(loginId.toString(),authPermissionPrefix);
    }

    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        return getAuth(loginId.toString(),authRolePrefix);
    }

    public List<String> getAuth(String loginId,String prefix){
        String authKey = redisUtil.buildKey(prefix, loginId.toString());
        String authValue =  redisUtil.get(authKey);
        if (StringUtils.isBlank(authValue)){
            return Collections.emptyList();
        }

        // 根据 prefix 判断是角色还是权限，再根据不同的 prefix 返回不同的 authList
        List<String> authList = new LinkedList<>();
        if (authRolePrefix.equals(prefix)){
            List<AuthRole> roleList = new Gson().fromJson(authValue, new TypeToken<List<AuthRole>>() {
            }.getType());
            authList = roleList.stream().map(AuthRole::getRoleKey).collect(Collectors.toList());
        }else if (authPermissionPrefix.equals(prefix)){
            List<AuthPermission> permissionList = new Gson().fromJson(authValue, new TypeToken<List<AuthPermission>>() {
            }.getType());
            authList = permissionList.stream().map(AuthPermission::getPermissionKey).collect(Collectors.toList());
        }
        return authList;
    }

}

